package bmatch.tech.todo.resource;

import bmatch.tech.todo.dao.BmUserMapper;
import bmatch.tech.todo.model.LoginUser;
import bmatch.tech.todo.model.Result;
import bmatch.tech.todo.model.UserStatus;
import bmatch.tech.todo.service.LoginService;
import bmatch.tech.todo.util.FormatUtils;
import bmatch.tech.todo.util.JwtUtils;
import bmatch.tech.todo.util.PwdUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import java.net.URI;

/**
 * @program:todo
 * @author:LinJinhao
 * @create:2019-01-23 17:43
 **/
@Component
@Path("/")
public class LoginResource {

	@Autowired
	private LoginService loginService;
	@Autowired
	private BmUserMapper bmUserMapper;

	/**
	*   登录
	**/
	@POST
	@Path("login")
	@Produces(MediaType.APPLICATION_JSON)

	public Response Login(@DefaultValue("") @QueryParam("email") String email,
	                      @DefaultValue("") @QueryParam("pwd") String pwd){
		Result result = new Result();

		//检查邮箱格式
		if (!FormatUtils.checkEmail(email) && StringUtils.isEmpty(email)){
			result.setErrorCode(Result.RESPONSE_FAIL);
			result.setSuccess(false);
			result.setErrorMessage("邮箱格式不正确，请重新输入");
			return Response.accepted(result).build();
		}

		//检查邮箱是否激活
		if (!bmUserMapper.selectByEmail(email).getStatus().equals(UserStatus.ENABLED.toString())){
			result.setErrorCode(Result.RESPONSE_FAIL);
			result.setSuccess(false);
			result.setErrorMessage("邮箱未激活，请激活！");
			return Response.accepted(result).build();
		}

		//使用加密的密码与数据库比较
		String encryptedPwd = PwdUtils.md5Password(pwd, "bmatch");
		LoginUser loginUser = loginService.login(email,encryptedPwd);
		//获取用户id
		String userId = bmUserMapper.selectByEmail(email).getId();


		if (loginUser != null){
			//生成一个token
			String token = JwtUtils.generator(userId);

			result.setErrorCode(Result.RESPONSE_SUCCESS);
			result.setSuccess(true);
			result.setErrorMessage("登录成功！");
			URI uri = URI.create("/main/get_user");
			return Response
					.seeOther(uri)
					.cookie(new NewCookie("sid",token)).build();
		} else{
			result.setErrorCode(Result.RESPONSE_FAIL);
			result.setSuccess(false);
			result.setErrorMessage("密码不正确，请重新输入");

			return Response.accepted(result).build();
		}
	}

}
